package cn.qidisoft.edu.hzjt.controller.xb;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.ConvertUtils;
import org.apache.commons.beanutils.converters.DateConverter;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSONObject;

import cn.qidisoft.core.common.context.ApplicationContextConfigUtil;
import cn.qidisoft.core.common.log.LoggerAdapter;
import cn.qidisoft.core.common.log.LoggerAdapterFactory;
import cn.qidisoft.core.common.pagination.Page;
import cn.qidisoft.core.common.pagination.PaginationBean;
import cn.qidisoft.core.util.DateUtil;
import cn.qidisoft.core.util.file.FileUtil;
import cn.qidisoft.core.util.moffice.excel.ExpExcelUtil;
import cn.qidisoft.core.util.uuid.UUIDGenerator;
import cn.qidisoft.edu.hzjt.annotation.SysLogger;
import cn.qidisoft.edu.hzjt.constants.Constant;
import cn.qidisoft.edu.hzjt.controller.BaseController;
import cn.qidisoft.edu.hzjt.exception.RPCException;
import cn.qidisoft.edu.hzjt.model.BjxxClassMaterialFile;
import cn.qidisoft.edu.hzjt.model.ResponseResult;
import cn.qidisoft.edu.hzjt.model.UserEmployee;
import cn.qidisoft.edu.hzjt.model.xb.PartyEmploySuperviseAttEn;
import cn.qidisoft.edu.hzjt.model.xb.PartyEmploySuperviseEn;
import cn.qidisoft.edu.hzjt.service.xb.IPartyEmploySuperviseAttService;
import cn.qidisoft.edu.hzjt.service.xb.IPartyEmploySuperviseService;
import cn.qidisoft.edu.hzjt.utils.CommonUtils;
import cn.qidisoft.edu.hzjt.utils.LogType;

/**
 * 
 * @ClassName: partyEmploySuperviseController   
 * @Description:五、教师招聘监督工作情况
 * @author xb12369   
 * @date 2018年11月21日   
 *
 */
@Controller
@RequestMapping(value="/partyEmploySupervise")
public class PartyEmploySuperviseController {

	protected static final LoggerAdapter LOGGER = LoggerAdapterFactory.getLogger(LogType.HZJT_LOGGER.val);

	private static String upload = null;
	static {
		upload = ApplicationContextConfigUtil.getString("file.path", null);
	}

	private static Map<String, List<PartyEmploySuperviseAttEn>> picMap = new HashMap<>();

	@Autowired
	private IPartyEmploySuperviseService service;
	
	@Autowired
	private IPartyEmploySuperviseAttService partyEmploySuperviseAttrService;
	

	@RequestMapping(value = "/index")
	public String index(ModelMap model, HttpServletRequest request) {
		request.setAttribute("msg", BaseController.getParameter("msg"));
		BaseController.removeParameter("msg");
		
		//获取年份list
		List<Map<String, Object>>  yearList = service.queryAllYearList();
		request.setAttribute("yearList", yearList);
		return "xb/ZHDJ_DFLZ_JSZPJD/list_PartyEmploySupervise";
	}

	@RequestMapping(value = "/list")
	@ResponseBody
	public ResponseResult list(
			ModelMap model, HttpServletRequest request,
			@RequestParam(value = "rows", required = false) String pageSize,
			@RequestParam(value = "page", required = false) String currentPage,
			PartyEmploySuperviseEn data) {
		try {
			data.setGID(UUIDGenerator.genReqID());
			Page page = new Page();
			page.setCurrPage(currentPage == null ? 0 : Integer.valueOf(currentPage));
			page.setPageSize(pageSize == null ? Constant.PageSize : Integer.valueOf(pageSize));
			BaseController.setSortByColumn(request, "createtime", "desc");
			data.setOrderField((String) request.getAttribute("orderField"));
			data.setOrderFlag((String) request.getAttribute("orderFlag"));
			PaginationBean<PartyEmploySuperviseEn> paginationBean = service.queryPageList(data,page);
			ResponseResult result = new ResponseResult();
			result.setTotal(paginationBean.getTotalRecords());
			result.setRows(paginationBean.getPageList());
			return result;
		} catch (Exception e) {
			LOGGER.error(e.getMessage(), e);
		}
		return null;
	}
	
	/**
	 * 
	 * @Title: add   
	 * @Description: 详情页面
	 * 1、点击标题的超链接直接看详情
	 * 2、新增页面点击“保存”按钮跳转
	 * @param @param model
	 * @param @param request
	 * @param @return    参数   
	 * @return String    返回类型   
	 * @throws
	 */
	@RequestMapping(value = "/info", method = RequestMethod.GET)
	public String info(ModelMap model, HttpServletRequest request) {
		try {
			//获取详情
			String id = request.getParameter("id") == null ? "0" : request.getParameter("id");
			String gid = request.getParameter("gid");
			PartyEmploySuperviseEn PartyEmploySuperviseEn = new PartyEmploySuperviseEn();
			PartyEmploySuperviseEn.setjdId(Integer.parseInt(id));
			PartyEmploySuperviseEn.setGID(gid);

			PartyEmploySuperviseEn entityInfo = service.queryByPK(PartyEmploySuperviseEn);
			model.addAttribute("entity", entityInfo);

			//获取附件信息
			PartyEmploySuperviseAttEn att = new PartyEmploySuperviseAttEn();
			att.setParentId(entityInfo.getjdId());
			List<PartyEmploySuperviseAttEn> attList = partyEmploySuperviseAttrService.queryList(att);
			model.addAttribute("dataList", attList);

			request.setAttribute("msg", BaseController.getParameter("msg"));
			BaseController.removeParameter("msg");
		} catch (Exception e) {
			e.printStackTrace();

			LOGGER.error("查询 queryByPK [{}] error," + this.getClass().getName() + "=[{}]",
					this.getClass().getName(), e.getMessage());
			model.addAttribute(Constant.EXPTION_MSG_KEY, e);
			return "error/error";
		}

		return "xb/ZHDJ_DFLZ_JSZPJD/info_PartyEmploySupervise";
	}

	@RequestMapping(value = "/addInInt", method = RequestMethod.GET)
	public String add(ModelMap model, HttpServletRequest request) {
		try {
			PartyEmploySuperviseEn entityInfo = new PartyEmploySuperviseEn();
			//获取详情
			String id = request.getParameter("id") ;
			if(!StringUtils.isEmpty(id)) {
				PartyEmploySuperviseEn PartyEmploySuperviseEn = new PartyEmploySuperviseEn();
				PartyEmploySuperviseEn.setjdId(Integer.parseInt(id));
				entityInfo = service.queryByPK(PartyEmploySuperviseEn);

				//获取附件信息
				PartyEmploySuperviseAttEn att = new PartyEmploySuperviseAttEn();
				att.setParentId(PartyEmploySuperviseEn.getjdId());
				List<PartyEmploySuperviseAttEn> attList = partyEmploySuperviseAttrService.queryList(att);
				model.addAttribute("dataList", attList);
			}
			model.addAttribute("entity", entityInfo);
			
			request.setAttribute("msg", BaseController.getParameter("msg"));
            BaseController.removeParameter("msg");
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		return "xb/ZHDJ_DFLZ_JSZPJD/modify_PartyEmploySupervise";
	}

	@SysLogger(description = "教师招聘监督工作情况管理信息", moduleName = "教师招聘监督工作情况管理", method = "新增保存")
	@RequestMapping(value = "/save", method = RequestMethod.POST)
	public String save(HttpServletRequest request,PartyEmploySuperviseEn data) {
		try {
			String type = request.getParameter("urlTp");//1#add保存（跳转info）|2#add保存并新增（跳转addInInt）|3#modify保存（跳转列表index）
			if(StringUtils.isEmpty(type)) {
				BaseController.setParameter("msg", "参数type丢失");
				return "redirect:index";
			}

			UserEmployee userEmployee = (UserEmployee) request.getSession().getAttribute(Constant.LOGIN_CONSOLE_USER);
			String gid = UUIDGenerator.genReqID();
			data.setGID(gid);
			data.setCreatorId(userEmployee.getUid());
			data.setCreatorName(userEmployee.getXm());
			data.setCreateTime(DateUtil.formatDate2Str((new Date()), DateUtil.YYYY_MM_DD_FORMAT));

			if(data.getjdId()!=0) {
				PartyEmploySuperviseEn newData = new PartyEmploySuperviseEn();
				ConvertUtils.register(new DateConverter(null), java.util.Date.class);
				BeanUtils.copyProperties(newData,data);
				
				service.update(newData);
				
				BaseController.setParameter("msg", "修改成功");
			}else {
				service.insert(data);
				
				BaseController.setParameter("msg", "添加成功");
				
				//这里还是要查询下，得到id
				PartyEmploySuperviseEn queryData = service.queryByPK(data);
				data.setjdId(queryData.getjdId());
			}

			String path = upload;
			List<PartyEmploySuperviseAttEn> docFileResourceList = picMap.get(String.valueOf(userEmployee.getUserid()));
			if (docFileResourceList != null && !docFileResourceList.isEmpty()) {
				MultipartFile file = null;
				String filePath =CommonUtils.createSaveFilePath("ZHDJ_DFLZ_JSZPJD", userEmployee.getUserid() ); 
				for (PartyEmploySuperviseAttEn r : docFileResourceList) {
					file = r.getMufile();
					r.setParentId(data.getjdId());
					String name = file.getOriginalFilename();// 获取上传文件名
					InputStream in = r.getInputStream();// 获取文件对象
					int pos = name.lastIndexOf(".");
					String lastname = name.substring(pos, name.length());
					// 文件保存的路径
					String savePath = path +CommonUtils.fileSeprator+ filePath;
					FileUtil.saveFile(savePath, in, r.getGid() + lastname);
					r.setGid(r.getGid());// 附件id
					r.setFileName(name);
					r.setParentId(data.getjdId());
				}
				partyEmploySuperviseAttrService.batchInserts(docFileResourceList);
				//一旦上传成功需要清空，否则下一次上传的时候又刚一遍了~
				picMap.remove(String.valueOf(userEmployee.getUserid()));
			}
			

			if("1".equals(type)) {
				return "redirect:info?gid="+data.getGID();//1#add保存（跳转info）
			}else if("2".equals(type)) {
				return "redirect:addInInt";//2#add保存并新增（跳转addInInt）
			}else if("3".equals(type)) {
				return "redirect:index";//3#modify保存（跳转列表index）
			}else {
				BaseController.setParameter("msg", "参数非法");
				return "redirect:index";
			}

		} catch (Exception e) {
			e.printStackTrace();
			LOGGER.error("添加信息 add [{}] error," + this.getClass().getName() + "=[{}]",
					this.getClass().getName(), e.getMessage());
			return "error/error";
		}
	}

	@RequestMapping(value = "/delete", method = RequestMethod.POST)
	public String delete(ModelMap model, HttpServletRequest request) {
		try {
			String[] idList = request.getParameter("idList").split(",");
			for (int i = 0; i < idList.length; i++) {
				PartyEmploySuperviseEn data = new PartyEmploySuperviseEn();
				data.setjdId(Integer.parseInt(idList[i]));
				service.delete(data);
			}

			BaseController.setParameter("msg", "删除成功");
			return "redirect:index";
		} catch (Exception e) {
			e.printStackTrace();
			LOGGER.error("删除 delete [{}] error," + this.getClass().getName() + "=[{}]",
					this.getClass().getName(), e.getMessage());
			return "error/error";
		}
	}
	
	/**
	 * 
	 * @Title: loadFile   
	 * @Description: 附件上传
	 * @param @param file
	 * @param @param request
	 * @param @param response    参数   
	 * @return void    返回类型   
	 * @throws
	 */
	@RequestMapping(value = "/source_upload", method = RequestMethod.POST)
	public @ResponseBody void source_upload(@RequestParam("file") MultipartFile file,
			HttpServletRequest request, HttpServletResponse response) {
		List<PartyEmploySuperviseAttEn> list = new ArrayList<>();
		UserEmployee userEmployee = (UserEmployee) request.getSession()
				.getAttribute(Constant.LOGIN_CONSOLE_USER);
		List<PartyEmploySuperviseAttEn> docFileResourceList = picMap
				.get(String.valueOf(userEmployee.getUserid()));
		// 本地env配置路径
		String path = upload;
		try {
			String gid = UUID.randomUUID().toString();
			String name = file.getOriginalFilename();// 获取上传文件名
			// 获取文件后缀名称
			String extend = FilenameUtils.getExtension(name);
			PartyEmploySuperviseAttEn docFile = new PartyEmploySuperviseAttEn();
			String filePath =CommonUtils.createSaveFilePath("ZHDJ_DFLZ_JSZPJD", userEmployee.getUserid() );
			if (!file.isEmpty()) {
				// 文件的大小
				docFile.setFileSize(String.valueOf(FileUtil.FormetFileSize(Long.valueOf(file.getSize()))));
				docFile.setFileName(name);
				docFile.setGid(gid);
				docFile.setExtension(FileUtil.getFileExtendName(name).toLowerCase());
				docFile.setMufile(file);
				docFile.setInputStream(file.getInputStream());
				
				/**
				 * 2018年12月9日 
				 * 当前业务目录/用户ID/上传当前时间（到天）/随机生成uuid文件名称
				 */
				docFile.setFilePath(filePath + gid + "." + extend);
				docFile.setSysfilepath(path + CommonUtils.fileSeprator+ filePath + gid + "." + extend);
				
				docFile.setOrders(0);
				if (docFileResourceList != null && docFileResourceList.size() > 0) {
					docFileResourceList.add(docFile);
					picMap.put(String.valueOf(userEmployee.getUserid()), docFileResourceList);
				} else {
					list.add(docFile);
					picMap.put(String.valueOf(userEmployee.getUserid()), list);
				}
				LOGGER.info("附件上传成功！");
			}
			PrintWriter writer = null;
			BjxxClassMaterialFile docFile2 = new BjxxClassMaterialFile();
			docFile2.setFilepath(docFile.getFilePath());
			// 文件名称
			docFile2.setFilename(docFile.getFileName());
			docFile2.setSysfilepath(path + CommonUtils.fileSeprator+ filePath + gid + "." + extend);
			writer = response.getWriter();
			String json = JSONObject.toJSONString(docFile2);
			writer.write(json);
			writer.flush();
			writer.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 
	 * @Title: source_upload_update   
	 * @Description: 删除附件
	 * @param @param fileId  
	 * @param @param request
	 * @param @param response
	 * @param @return    参数   
	 * @return Map<String,Object>    返回类型   
	 * @throws
	 */
	@RequestMapping(value = "/source_upload_update", method = RequestMethod.POST)
	public @ResponseBody Map<String, Object> source_upload_update(@RequestParam("fileId") String fileId,
			@RequestParam("filePath") String filePath,
			HttpServletRequest request,
			HttpServletResponse response) {
		Map<String, Object> dataMap = new HashMap<String, Object>();
		try {
			//删除表记录
			PartyEmploySuperviseAttEn attEntity = new PartyEmploySuperviseAttEn();
			attEntity.setFileId(Integer.parseInt(fileId));
			
			PartyEmploySuperviseAttEn newAttEntity = partyEmploySuperviseAttrService.queryByFileId(attEntity);
			filePath = newAttEntity.getFilePath();
			partyEmploySuperviseAttrService.delete(newAttEntity);
			
			//删除原始文件
			File file = new File(upload + CommonUtils.fileSeprator+ filePath);
			file.delete();
			
			//删除目录：实际上是删除最后一节也就是日期文件夹
			try {
				FileUtils.forceDelete(new File(upload + CommonUtils.fileSeprator+ filePath.substring(0,filePath.lastIndexOf("\\")))); //如果文件中所有的文件被删除了，还需要删除文件目录
			} catch (Exception e) {

			}
			
			dataMap.put("success", "0000");
		} catch (Exception e) {
			LOGGER.error("调用services网络异常", e);
			dataMap.put("success", "-9999");
		}
		return dataMap;
	}

	/**
	 * 
	 * @Title: exportpartyEmploySupervise   
	 * @Description: 列表数据导出
	 * @param @param request
	 * @param @param response
	 * @param @param data
	 * @param @param model
	 * @param @return
	 * @param @throws Exception    参数   
	 * @return String    返回类型   
	 * @throws
	 */
	@RequestMapping(value = "/exportpartyEmploySupervise")
	public @ResponseBody String exportpartyEmploySupervise(HttpServletRequest request,
			HttpServletResponse response, PartyEmploySuperviseEn data, ModelMap model) throws Exception {
		try {
			List<PartyEmploySuperviseEn> queryList = service.queryList(data);

			String[][] title_name = {{"年份", "备注","创建人", "创建时间"}};
			String[] title_style = {"hwzs_16_bold_25", "kt_12_bold_18", "st_12_r_20", "st_12_n_20"};
			String fileName = "教师招聘监督工作情况";
			String[] remark = {""};
			List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
			if (queryList != null && !queryList.isEmpty()) {
				for (PartyEmploySuperviseEn res : queryList) {
					Map<String, Object> map = new LinkedHashMap<String, Object>();
					map.put("jDNFYear", res.getjDNFYear());
					map.put("remark", res.getRemark());
					map.put("creatorName", res.getCreatorName());
					map.put("createTime", res.getCreateTime());
					list.add(map);
				}
			}
			HSSFWorkbook wb = ExpExcelUtil.getWorkBookExcel(title_name, title_style, 100, remark, fileName, list);

			try {
				String filenameConvert = "教师招聘监督工作情况";/* new String(fileName.getBytes("GB2312"), "ISO8859-1"); */
				response.reset();
				response.setContentType("application/vnd.ms-excel;charset=utf-8");
				response.setHeader("Content-Disposition", "attachment;filename="+ new String((filenameConvert + ".xls").getBytes(), "iso-8859-1"));
				response.setDateHeader("Expires", 0);
				ServletOutputStream os = response.getOutputStream();
				wb.write(os);
				os.flush();
			} catch (Exception e) {
				System.out.println("网络连接断开，可能用户取消了导出");
				model.addAttribute(Constant.EXPTION_MSG_KEY, e);
				return "error/error";
			}
		} catch (RPCException e) {
			LOGGER.error("获得教师招聘监督工作情况 exportStudentjobList [{}] error," + this.getClass().getName() + "=[{}]",
					this.getClass().getName(), e.getMessage());
			model.addAttribute(Constant.EXPTION_MSG_KEY, e);
			return "error/error";
		}
		return null;
	}
	
	
	
	
	/*********************************************************************华丽的分隔符******************************************************************************/
	@RequestMapping(value = "/index2")
	public String index2(ModelMap model, HttpServletRequest request) {
		request.setAttribute("msg", BaseController.getParameter("msg"));
		BaseController.removeParameter("msg");
		
		//获取年份list
		List<Map<String, Object>>  yearList = service.queryAllYearList();
		request.setAttribute("yearList", yearList);
		return "xb/ZHDJ_DFLZ_JSZPJD/list_PartyEmploySupervise2";
	}

	@RequestMapping(value = "/list2")
	@ResponseBody
	public ResponseResult list2(
			ModelMap model, HttpServletRequest request,
			@RequestParam(value = "rows", required = false) String pageSize,
			@RequestParam(value = "page", required = false) String currentPage,
			PartyEmploySuperviseEn data) {
		try {
			data.setGID(UUIDGenerator.genReqID());
			Page page = new Page();
			page.setCurrPage(currentPage == null ? 0 : Integer.valueOf(currentPage));
			page.setPageSize(pageSize == null ? Constant.PageSize : Integer.valueOf(pageSize));
			BaseController.setSortByColumn(request, "createtime", "desc");
			data.setOrderField((String) request.getAttribute("orderField"));
			data.setOrderFlag((String) request.getAttribute("orderFlag"));
			PaginationBean<PartyEmploySuperviseEn> paginationBean = service.queryPageList2(data,page);
			ResponseResult result = new ResponseResult();
			result.setTotal(paginationBean.getTotalRecords());
			result.setRows(paginationBean.getPageList());
			return result;
		} catch (Exception e) {
			LOGGER.error(e.getMessage(), e);
		}
		return null;
	}
	
	
	
	/**
	 * 
	 * @Title: exportpartyEnrollSupervise   
	 * @Description: 列表数据导出
	 * @param @param request
	 * @param @param response
	 * @param @param data
	 * @param @param model
	 * @param @return
	 * @param @throws Exception    参数   
	 * @return String    返回类型   
	 * @throws
	 */
	@RequestMapping(value = "/exportpartyEmploySupervise2")
	public @ResponseBody String exportpartyEmploySupervise2(HttpServletRequest request,
			HttpServletResponse response, PartyEmploySuperviseEn data, ModelMap model) throws Exception {
		try {
			Page page = new Page();
			page.setCurrPage(1);
			page.setPageSize(99999);
			List<PartyEmploySuperviseEn> queryList = service.exportList(data, page);

			String[][] title_name = {{"序号","年份", ""}};
			String[] title_style = {"hwzs_16_bold_25", "kt_12_bold_18", "st_12_r_20"};
			String fileName = "教师招聘监督工作情况汇总";
			String[] remark = {""};
			List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
			if (queryList != null && !queryList.isEmpty()) {
				StringBuffer bf = null;
				for (PartyEmploySuperviseEn res : queryList) {
					bf = new StringBuffer();
					Map<String, Object> map = new LinkedHashMap<String, Object>();
					map.put("rownumber", res.getRownumber());
					map.put("jDNFYear", res.getjDNFYear());
					
					for (PartyEmploySuperviseAttEn en : res.getAttList()) {
						bf.append(en.getFileName() + ",");
					}
					
					if(!StringUtils.isEmpty(bf.toString())) {
						map.put("fileList2", bf.toString().substring(0,(bf.toString().length()-1)));
					}else {
						map.put("fileList2", "");
					}
					
					list.add(map);
				}
			}
			HSSFWorkbook wb = ExpExcelUtil.getWorkBookExcel(title_name, title_style, 100, remark, fileName, list);

			try {
				String filenameConvert = "教师招聘监督工作情况汇总";/* new String(fileName.getBytes("GB2312"), "ISO8859-1"); */
				response.reset();
				response.setContentType("application/vnd.ms-excel;charset=utf-8");
				response.setHeader("Content-Disposition", "attachment;filename="+ new String((filenameConvert + ".xls").getBytes(), "iso-8859-1"));
				response.setDateHeader("Expires", 0);
				ServletOutputStream os = response.getOutputStream();
				wb.write(os);
				os.flush();
			} catch (Exception e) {
				System.out.println("网络连接断开，可能用户取消了导出");
				model.addAttribute(Constant.EXPTION_MSG_KEY, e);
				return "error/error";
			}
		} catch (RPCException e) {
			LOGGER.error("获得教师招聘监督工作情况汇总 exportStudentjobList [{}] error," + this.getClass().getName() + "=[{}]",
					this.getClass().getName(), e.getMessage());
			model.addAttribute(Constant.EXPTION_MSG_KEY, e);
			return "error/error";
		}
		return null;
	}
}
